package com.xingzhi.shortvideosharingplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xingzhi.shortvideosharingplatform.dto.FollowingUserDTO;
import com.xingzhi.shortvideosharingplatform.dto.UserFollowDTO;
import com.xingzhi.shortvideosharingplatform.mapper.UserFollowMapper;
import com.xingzhi.shortvideosharingplatform.model.UserFollow;
import com.xingzhi.shortvideosharingplatform.service.SystemNotificationService;
import com.xingzhi.shortvideosharingplatform.service.UserBehaviorLogsService;
import com.xingzhi.shortvideosharingplatform.service.UserFollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements UserFollowService {

    @Autowired
    private UserBehaviorLogsService behaviorLogsService;
    
    @Autowired
    private SystemNotificationService notificationService;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean isFollowed(Long followerId, Long followingId) {
        try {
            LambdaQueryWrapper<UserFollow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserFollow::getFollowerId, followerId)
                      .eq(UserFollow::getFollowingId, followingId);
            return count(queryWrapper) > 0;
        } catch (Exception e) {
            log.error("检查用户关注状态失败: followerId={}, followingId={}", followerId, followingId, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean follow(UserFollowDTO followDTO) {
        // 参数校验
        if (followDTO == null || followDTO.getFollowerId() == null || 
            followDTO.getFollowingId() == null) {
            log.error("关注参数不完整");
            return false;
        }
        
        // 检查是否自己关注自己
        if (followDTO.getFollowerId().equals(followDTO.getFollowingId())) {
            log.error("不能关注自己");
            return false;
        }
        
        // 检查是否已经关注过
        if (isFollowed(followDTO.getFollowerId(), followDTO.getFollowingId())) {
            log.info("已经关注过该用户: followerId={}, followingId={}", 
                    followDTO.getFollowerId(), followDTO.getFollowingId());
            return true;
        }
        
        try {
            log.info("开始关注用户: followerId={}, followingId={}", 
                followDTO.getFollowerId(), followDTO.getFollowingId());
            
            // 1. 创建关注记录
            UserFollow userFollow = new UserFollow();
            userFollow.setFollowerId(followDTO.getFollowerId());
            userFollow.setFollowingId(followDTO.getFollowingId());
            userFollow.setGroupId(2L); // 默认分组ID为2
            userFollow.setIsSpecialFollow(0L); // 默认非特别关注
            userFollow.setCreatedTime(LocalDateTime.now());
            boolean saveResult = save(userFollow);
            
            if (!saveResult) {
                log.error("插入关注记录失败");
                return false;
            }
            
            // 2. 增加关注者的关注数
            String incrementFollowingSql = "UPDATE user_profiles SET following_count = following_count + 1 WHERE user_id = ?";
            jdbcTemplate.update(incrementFollowingSql, followDTO.getFollowerId());
            
            // 3. 增加被关注者的粉丝数
            String incrementFollowerSql = "UPDATE user_profiles SET follower_count = follower_count + 1 WHERE user_id = ?";
            jdbcTemplate.update(incrementFollowerSql, followDTO.getFollowingId());
            
            // 4. 发送系统通知（关注不记录用户行为）
            notificationService.sendFollowNotification(
                followDTO.getFollowingId(), // 接收通知的用户ID(被关注者)
                followDTO.getFollowerId()  // 关注用户ID
            );
            
            return true;
        } catch (Exception e) {
            log.error("关注用户失败: followerId={}, followingId={}", 
                followDTO.getFollowerId(), followDTO.getFollowingId(), e);
            throw e;
        }
    }

    @Override
    @Transactional
    public boolean unfollow(Long followerId, Long followingId) {
        // 参数校验
        if (followerId == null || followingId == null) {
            log.error("取消关注参数不完整");
            return false;
        }
        
        // 检查是否已关注
        if (!isFollowed(followerId, followingId)) {
            log.info("未关注该用户，无需取消: followerId={}, followingId={}", followerId, followingId);
            return false;
        }
        
        try {
            log.info("开始取消关注: followerId={}, followingId={}", followerId, followingId);
            
            // 1. 删除关注记录
            LambdaQueryWrapper<UserFollow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserFollow::getFollowerId, followerId)
                      .eq(UserFollow::getFollowingId, followingId);
            boolean success = remove(queryWrapper);
            
            if (!success) {
                log.error("删除关注记录失败");
                return false;
            }
            
            // 2. 减少关注者的关注数
            String decrementFollowingSql = "UPDATE user_profiles SET following_count = GREATEST(following_count - 1, 0) WHERE user_id = ?";
            jdbcTemplate.update(decrementFollowingSql, followerId);
            
            // 3. 减少被关注者的粉丝数
            String decrementFollowerSql = "UPDATE user_profiles SET follower_count = GREATEST(follower_count - 1, 0) WHERE user_id = ?";
            jdbcTemplate.update(decrementFollowerSql, followingId);
            
            // 注意：取消关注不发送系统通知
            
            return true;
        } catch (Exception e) {
            log.error("取消关注失败: followerId={}, followingId={}", followerId, followingId, e);
            throw e;
        }
    }
    
    @Override
    public List<FollowingUserDTO> getFollowingList(Long userId) {
        try {
            if (userId == null || userId <= 0) {
                log.error("获取关注列表参数不合法: userId={}", userId);
                return Collections.emptyList();
            }
            
            log.info("获取用户关注列表: userId={}", userId);
            return baseMapper.getFollowingList(userId);
        } catch (Exception e) {
            log.error("获取用户关注列表失败: userId={}", userId, e);
            return Collections.emptyList();
        }
    }
} 